package com.roin.learn.activiti.listener.activiti;

import com.roin.learn.activiti.command.CompleteTaskWithCommentCmd;
import com.roin.learn.activiti.service.ProcessService;
import com.roin.learn.activiti.utils.SpringContextUtil;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.ExecutionListener;
import org.activiti.engine.impl.cmd.CompleteTaskCmd;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.PvmActivity;
import org.activiti.engine.impl.pvm.PvmTransition;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.task.IdentityLink;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 自动完成任务监听器
 */
public class AutoCompleteTaskListener extends DefaultTaskListener {
    /** logger. */
    private static Logger logger = LoggerFactory.getLogger(AutoCompleteTaskListener.class);

    @Override
    public void onCreate(DelegateTask delegateTask) throws Exception {


        /*String initiatorId = Authentication.getAuthenticatedUserId();

        if (initiatorId == null) {
            return;
        }

        String assignee = delegateTask.getAssignee();

        if (assignee == null) {
            return;
        }


        if (!initiatorId.equals(assignee)) {
            return;
        }

        logger.debug("auto complete task : {}", delegateTask);
        for (IdentityLink identityLink : delegateTask.getCandidates()) {
            String userId = identityLink.getUserId();
            String groupId = identityLink.getGroupId();

            if (userId != null) {
                delegateTask.deleteCandidateUser(userId);
            }

            if (groupId != null) {
                delegateTask.deleteCandidateGroup(groupId);
            }
        }*/
        // ((TaskEntity) delegateTask).complete();
        // Context.getCommandContext().getHistoryManager().recordTaskId((TaskEntity) delegateTask);
        /*new CompleteTaskWithCommentCmd(delegateTask.getId(), null, "发起流程")
                .execute(Context.getCommandContext());*/



        String userId = Authentication.getAuthenticatedUserId();
        String assignee = delegateTask.getAssignee();

        ProcessDefinitionEntity processDefinitionEntity = Context.getProcessEngineConfiguration().getProcessDefinitionCache().get(delegateTask.getProcessDefinitionId());

        ActivityImpl startActivity = processDefinitionEntity.getInitial();

        if (startActivity.getOutgoingTransitions().size() != 1) {
            throw new IllegalStateException("start activity outgoing transitions cannot more than 1, now is : " + startActivity.getOutgoingTransitions().size());
        }

        PvmTransition pvmTransition = startActivity.getOutgoingTransitions().get(0);
        PvmActivity targetActivity = pvmTransition.getDestination();

        if (!"userTask".equals(targetActivity.getProperty("type"))) {
            logger.debug("first activity is not userTask, just skip");
            return;
        }

        if (targetActivity.getId().equals(delegateTask.getExecution().getCurrentActivityId())) {
            if ((userId != null) && userId.equals(assignee)) {
                logger.debug("auto complete first task : {}", delegateTask);
                   // new CompleteTaskCmd(delegateTask.getId(),null).execute(Context.getCommandContext());
//                new CompleteTaskWithCommentCmd(delegateTask.getId(), null, "发起流程").execute(Context.getCommandContext());
            }
        }
    }

}
